package com.egdigital.allzic.ui.fragment;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.egdigital.allzic.R;
import com.egdigital.allzic.data.json.JsonCacheManager;
import com.egdigital.allzic.data.json.JsonCallBack;
import com.egdigital.allzic.data.json.JsonParserStation;
import com.egdigital.allzic.data.json.VolleyManager;
import com.egdigital.allzic.data.object.Station;
import com.egdigital.allzic.service.ServiceStreaming;
import com.egdigital.allzic.ui.activity.ActivityMain;
import com.egdigital.allzic.ui.adapter.AdapterListRadio;
import com.egdigital.allzic.utils.NetworkManager;

public class FragmentExploreDiscover extends BaseMainFragment implements OnItemClickListener, JsonCallBack, OnClickListener {

	private static final String		TAG					= FragmentExploreDiscover.class.getSimpleName();	// log
	private List<Station>			mList;
	private JsonParserStation		mJsonParser;
	//
	private ListView				mListView;
	private AdapterListRadio		mAdapter;
	private TextView				mTitle;
	private ImageButton				mcloseButton;
	// network ui
	protected ActivityMain			mParent;
	protected View					mView;
	final public BroadcastReceiver	mPlayBackReceiver	= new BroadcastReceiver() {

															@Override
															public void onReceive(Context context, Intent intent) {
																String actionString = intent.getAction();
																if (actionString == ServiceStreaming.SERVICE_PLAY) {
																} else if (actionString == ServiceStreaming.SERVICE_STOP) {
																} else if (actionString == ServiceStreaming.SERVICE_LOADING) {
																} else if (actionString == ServiceStreaming.SERVICE_ERROR) {
																} else if (actionString == ServiceStreaming.SERVICE_KILLED) {
																}
															}
														};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// receiver
		LocalBroadcastManager.getInstance(mParent).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_PLAY));
		LocalBroadcastManager.getInstance(mParent).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_STOP));
		LocalBroadcastManager.getInstance(mParent).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_LOADING));
		LocalBroadcastManager.getInstance(mParent).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_ERROR));
		LocalBroadcastManager.getInstance(mParent).registerReceiver((mPlayBackReceiver), new IntentFilter(ServiceStreaming.SERVICE_KILLED));
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_list_radio_no_like, container, false);
		mLoadingView = (RelativeLayout) mView.findViewById(R.id.fragment_radio_nolike_loading);
		mReloadView = (LinearLayout) mView.findViewById(R.id.fragment_radio_nolike_reload);
		mNoResultView = (TextView) mView.findViewById(R.id.fragment_radio_nolike_noresult);
		//
		mListView = (ListView) mView.findViewById(R.id.fragment_category_radio_list);
		mTitle = (TextView) mView.findViewById(R.id.fragment_category_radio_title);
		mcloseButton = (ImageButton) mView.findViewById(R.id.fragment_category_radio_close);
		return mView;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		mView.setOnTouchListener(new View.OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				return true;
			}
		});
		mTitle.setText(getString(R.string.fragment_explore_discover));
		mListView.setOnItemClickListener(this);
		mcloseButton.setOnClickListener(this);
		mReloadView.setOnClickListener(this);
		super.onViewCreated(view, savedInstanceState);
	}

	@Override
	public void onResume() {
		super.onResume();
		if (mParent != null) {
			VolleyManager.init(mParent);
		}
		if (mJsonParser == null) {
			mJsonParser = new JsonParserStation();
		}
		mJsonParser.setJsonCallBack((JsonCallBack) this);
		if (mList == null || mList.isEmpty()) {
			mJsonParser.initAndStartRequestQueue();
		}
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.reload_layout:
				loadData();
				break;
			case R.id.fragment_category_radio_close:
				mParent.removeFragment();
				break;
		}
	}

	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		if (mParent != null) {
			Station station = mList.get(position);
			mParent.prepareToPlay(station);
			mParent.showPlayerBanner();
			mParent.updatePlayerBanner();
		}
	}

	/**
	 * animation
	 */
	@SuppressLint("NewApi")
	@Override
	public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
		Animation animation = super.onCreateAnimation(transit, enter, nextAnim);
		if (animation == null && nextAnim != 0) {
			animation = AnimationUtils.loadAnimation(getActivity(), nextAnim);
		}
		if (animation != null) {
			animation.setAnimationListener(new AnimationListener() {

				public void onAnimationEnd(Animation animation) {
					getView().post(new Runnable() {

						@Override
						public void run() {
							try {
								loadData();
							} catch (Exception e) {
							}
						}
					});
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationStart(Animation animation) {
				}
			});
		}
		return animation;
	}

	/**
	 * fragment life cycle
	 */
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mParent = (ActivityMain) activity;
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mParent.mExplorerSelected = false;
		mParent = null;
		mJsonParser.stopRequestQueue();
	}

	@Override
	public void onDestroy() {
		if (mPlayBackReceiver != null) {
			LocalBroadcastManager.getInstance(mParent).unregisterReceiver(mPlayBackReceiver);
		}
		super.onDestroy();
	}

	/**
	 * methods
	 */
	private void loadData() {
		if (NetworkManager.isConnected(mParent.getApplicationContext())) {
			// url
			String url = getString(R.string.url_decouvrir);
			List<Station> list = JsonCacheManager.getStations(mParent.getApplicationContext(), JsonCacheManager.FAVORITE_STATION);
			for (int i = 0; i < list.size(); i++) {
				url += list.get(i).getmId();
				if (i < list.size() - 1) {
					url += "-";
				}
			}
			mJsonParser.extractJsonObjectData(url);
		} else {
			mListView.setVisibility(View.GONE);
		}
	}

	private void updateAdapter(List<Station> list) {
		mAdapter = null;
		mAdapter = new AdapterListRadio(mParent.getApplicationContext(), list, R.layout.cell_list_radio);
		mListView.setVisibility(View.VISIBLE);
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(this);
	}

	/**
	 * volley callback
	 */
	@Override
	public void downloadStarted() {
		setLoading(mListView);
	}

	@Override
	public void downloadPercent(int percent) {
		// do nothing
	}

	@Override
	public <T> void downloadCompleted(List<T> list) {
		if (mParent == null || list == null) {
			return;
		}
		if (!list.isEmpty()) {
			setLoaded(mListView);
			mList = (List<Station>) list;
			// sort
			Collections.sort(mList, new Comparator<Object>() {

				public int compare(Object o1, Object o2) {
					Station p1 = (Station) o1;
					Station p2 = (Station) o2;
					return p1.getmTitle().compareToIgnoreCase(p2.getmTitle());
				}
			});
			updateAdapter(mList);
		} else {
			setReload(mListView);
		}
	}

	@Override
	public void downloadEndedWithError(VolleyError error) {
		setReload(mListView);
	}
}
